import {Button, message, Pagination, Space, Table, Tag} from "antd";
import {useEffect, useState} from "react";
import {ClockCircleOutlined, EyeOutlined, ReloadOutlined, RetweetOutlined} from "@ant-design/icons";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import MqSearch from "../../../components/console/mq/mqSearch";
import MqDetail from "../../../components/console/mq/mqDetail";

/**
 * 消息队列分页查询页面
 * 优化点：
 * 1. 消息ID加宽并改为蓝色
 * 2. 主题和标签使用Tag组件包裹
 * 3. 消费状态使用彩色标签区分
 * 4. 生产时间使用深蓝绿色展示
 * 5. 重发次数调整字体和颜色
 */
const ConsoleMqPage = () => {
    const [messageApi, contextHolder] = message.useMessage();

    // 分页参数
    const [paginationReq, setPaginationReq] = useState({
        pageNum: 1,
        pageSize: 10
    });

    // 查询条件参数
    const [pageMessageReq, setPageMessageReq] = useState({
        topic: 'DEFAULT',
        messageId: '',
        status: 0
    });

    // 分页查询结果
    const [pageMessageResp, setPageMessageResp] = useState({
        total: 0,
        pageCount: 0,
        records: []
    });

    // 所有主题名称列表
    const [topicNames, setTopicNames] = useState([]);

    // 消息详情模态框组件
    const [messageDetailVisible, setMessageDetailVisible] = useState(false);

    // 消息详情实体类
    const [messageDetail, setMessageDetail] = useState({});

    /**
     * 表格列配置
     * 按需求优化了各字段的样式和展示方式
     */
    const pageMessageRespFields = [
        {
            title: "序号",
            key: "index",
            width: 80,
            align: 'center',
            render: (text, record, index) => (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: '#666',
                    fontWeight: 500
                }}>
                    {/* 计算跨页序号 */}
                    {(paginationReq.pageNum - 1) * paginationReq.pageSize + index + 1}
                </div>
            ),
            isShow: true
        },
        {
            title: "消息id",
            dataIndex: "messageId",
            key: "messageId",
            width: 300, // 1. 加宽消息ID列以容纳长ID
            align: 'left', // 左对齐更适合长文本阅读
            render: (text) => (
                <div style={{
                    color: '#1890ff', // 1. 消息ID改为蓝色
                    fontSize: '14px',
                    fontWeight: 500,
                    wordBreak: 'break-all', // 长ID自动换行
                    padding: '2px 0'
                }}>
                    {text || '无消息ID'}
                </div>
            ),
            isShow: true
        },
        {
            title: "主题",
            dataIndex: "topic",
            key: "topic",
            width: 140,
            align: 'center',
            render: (text) => (
                // 2. 主题使用灰色背景Tag包裹
                <Tag
                    color="default"
                    style={{
                        backgroundColor: '#ccffff', // 浅灰背景
                        color: '#003333',
                        border: 'none',
                        fontSize: '13px',
                        padding: '3px 10px',
                        borderRadius: '4px'
                    }}
                >
                    {text}
                </Tag>
            ),
            isShow: true
        },
        {
            title: "消息标签",
            dataIndex: "tag",
            key: "tag",
            width: 140,
            align: 'center',
            render: (text) => {
                if (!text) {
                    return (
                        <Tag
                            color="default"
                            style={{
                                backgroundColor: '#f5f5f5',
                                color: '#86909c',
                                border: 'none',
                                fontSize: '12px'
                            }}
                        >
                            无标签
                        </Tag>
                    );
                }
                // 2. 标签使用紫色系背景Tag包裹
                return (
                    <Tag
                        color="purple"
                        style={{
                            backgroundColor: '#f6f3ff', // 浅紫背景
                            color: '#722ed1', // 深紫文字
                            border: 'none',
                            fontSize: '13px',
                            padding: '3px 10px',
                            borderRadius: '4px'
                        }}
                    >
                        {text}
                    </Tag>
                );
            },
            isShow: true
        },
        {
            title: "消费状态",
            dataIndex: "status",
            key: "status",
            width: 140,
            align: 'center',
            render: (status) => {
                // 3. 消费状态使用不同颜色标签区分
                const statusMap = {
                    0: {label: "未消费", color: "orange"},
                    1: {label: "消费中", color: "blue"},
                    2: {label: "消费成功", color: "green"},
                    3: {label: "消费失败", color: "red"}
                };
                const config = statusMap[status] || {label: "未知状态", color: "default"};

                return (
                    <Tag
                        color={config.color}
                        style={{
                            fontSize: '13px',
                            padding: '3px 10px',
                            borderRadius: '4px',
                            fontWeight: 500
                        }}
                    >
                        {config.label}
                    </Tag>
                );
            },
            isShow: true // 显示状态标签，隐藏原状态描述
        },
        {
            title: "消费状态描述",
            dataIndex: "statusDesc",
            key: "statusDesc",
            isShow: false // 隐藏原始描述，改用状态标签
        },
        {
            title: "消息生产时间",
            dataIndex: "sendTime",
            key: "sendTime",
            width: 200,
            align: 'center',
            render: (time) => (
                <Space size="small" style={{alignItems: 'center'}}>
                    {/* 4. 生产时间使用深蓝绿色，添加时钟图标增强语义 */}
                    <ClockCircleOutlined style={{color: '#096b72', fontSize: '14px'}}/>
                    <span style={{
                        color: '#096b72', // 深蓝绿色
                        fontSize: '13px',
                        fontWeight: 500
                    }}>
                        {time || '未知时间'}
                    </span>
                </Space>
            ),
            isShow: true
        },
        {
            title: "重发次数",
            dataIndex: "retryCount",
            key: "retryCount",
            width: 140,
            align: 'center',
            render: (count) => (
                <Space size="small" style={{alignItems: 'center'}}>
                    {/* 5. 重发次数使用棕色系，添加重发图标，改用等宽字体突出数字 */}
                    <RetweetOutlined style={{color: '#ff0000', fontSize: '14px'}}/>
                    <span style={{
                        color: '#ff0000', // 棕色系
                        fontSize: '14px',
                        fontWeight: 'bolder'
                    }}>
                        {count}
                    </span>
                </Space>
            ),
            isShow: true
        },
        {
            title: '操作',
            align: 'center',
            render: (text, record) => (
                <Space size="small">
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EyeOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#1890ff',
                            backgroundColor: 'rgba(24, 144, 255, 0.05)',
                            border: '1px solid #91d5ff',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => {
                            setMessageDetail(record);
                            setMessageDetailVisible(true);
                        }}
                    >
                        详情
                    </Button>
                    <Button
                        size={"small"}
                        type="text"
                        icon={<ReloadOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#F3037B',
                            backgroundColor: '#FFE4F2',
                            border: '1px solid #FF0080',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = '#FFE4F2';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = '#FFE4F2';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => resendMessage(record.messageId)}
                    >
                        重发
                    </Button>
                </Space>
            ),
            isShow: true
        }
    ];

    /**
     * 分页查询消息
     * 整合分页参数和查询条件，调用接口获取数据
     */
    const pageQueryMessage = () => {
        RequestUtils.post(RequestApis.messageManage.page, {
            pageNum: paginationReq.pageNum,
            pageSize: paginationReq.pageSize,
            topic: pageMessageReq.topic,
            messageId: pageMessageReq.messageId,
            status: pageMessageReq.status
        }).then(res => setPageMessageResp(res.data.data))
            .catch(e => messageApi.error(e.message || "查询消息失败"));
    };

    /**
     * 查询所有主题名
     * 用于填充Topic下拉框选项
     */
    const searchAllTopicNames = () => {
        RequestUtils.post(RequestApis.messageManage.searchAllTopic, {})
            .then(res => {
                if (res.data.data) {
                    setTopicNames(res.data.data.map(item => item.topic));
                }
            }).catch(err => messageApi.error(err.message || "查询主题列表失败"));
    };

    /**
     * 重发消息
     * @param messageId
     */
    const resendMessage = (messageId) => {
        RequestUtils.post(RequestApis.messageManage.resendMessage, {
            id: messageId
        }).then(res => {
            pageQueryMessage();
            messageApi.success("重发成功");
        }).catch(err => messageApi.error(err.message));
    }

    /**
     * 监听分页参数变化，重新查询数据
     */
    useEffect(() => {
        pageQueryMessage();
        // eslint-disable-next-line
    }, [paginationReq]);

    /**
     * 页面初始化时查询主题列表
     */
    useEffect(() => {
        searchAllTopicNames();
        // eslint-disable-next-line
    }, []);

    /**
     * 表格行样式 - 交替行背景色
     * 增强行与行之间的区分度
     */
    const getRowClassName = (record, index) => {
        return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
    };

    return (
        <div>
            {contextHolder}

            {/* 查询条件区域 */}
            <div style={{
                padding: '16px',
                paddingBottom: '8px',
                backgroundColor: '#fff',
                borderRadius: '8px',
                marginBottom: '16px'
            }}>
                <MqSearch
                    topicNames={topicNames}
                    setPaginationReq={setPaginationReq}
                    pageMessageReq={pageMessageReq}
                    setPageMessageReq={setPageMessageReq}
                    pageQueryMessage={pageQueryMessage}
                />
            </div>

            {/* 表格展示区域 */}
            <div style={{
                backgroundColor: '#fff',
                borderRadius: '8px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.04)',
                overflow: 'hidden',
                transition: 'box-shadow 0.3s ease'
            }}
                 onMouseOver={(e) => {
                     e.currentTarget.style.boxShadow = '0 4px 16px rgba(0, 0, 0, 0.08)';
                 }}
                 onMouseOut={(e) => {
                     e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.04)';
                 }}>
                <Table
                    dataSource={pageMessageResp.records}
                    columns={pageMessageRespFields.filter(item => item.isShow)}
                    pagination={false}
                    scroll={{
                        y: 'calc(100vh - 460px)',
                        x: 'max-content'
                    }}
                    bordered={false}
                    rowHoverable
                    style={{width: '100%'}}
                    tableLayout="fixed"
                    rowClassName={getRowClassName}
                    headerStyle={{
                        backgroundColor: '#fafafa',
                        color: '#1f2329',
                        fontWeight: 600,
                        fontSize: '14px',
                        borderBottom: '1px solid #e5e6eb',
                        padding: '12px 16px'
                    }}
                    bodyStyle={{
                        fontSize: '13px'
                    }}
                    rowStyle={{
                        height: '60px',
                        transition: 'background-color 0.2s ease'
                    }}
                    // 表格加载状态
                    loading={{
                        spinning: false, // 可根据实际加载状态修改
                        indicator: <div style={{padding: '40px 0'}}>加载中...</div>
                    }}
                    // 行悬停样式
                    onRow={(record, index) => ({
                        onMouseEnter: (e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.02)';
                        },
                        onMouseLeave: (e) => {
                            const isEven = index % 2 === 0;
                            e.currentTarget.style.backgroundColor = isEven ? '#fcfcfc' : '#fff';
                        },
                    })}
                />
            </div>

            {/* 分页组件 */}
            <div style={{
                display: "flex",
                justifyContent: "flex-end",
                alignItems: "center",
                height: '60px',
                marginTop: '16px',
                fontSize: '13px'
            }}>
                <Pagination
                    total={pageMessageResp.total}
                    current={paginationReq.pageNum}
                    pageSize={paginationReq.pageSize}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => (
                        <div style={{fontSize: '15px'}}>
                            <span>共</span>
                            <span style={{color: 'red', fontWeight: 'bold'}}> {total} </span>
                            <span>条数据</span>
                        </div>
                    )}
                    pageSizeOptions={['10', '20', '50', '100', '200']}
                    onChange={(pageNum, pageSize) => {
                        setPaginationReq({...paginationReq, pageNum, pageSize});
                    }}
                    onShowSizeChange={(current, size) => {
                        setPaginationReq({...paginationReq, pageNum: current, pageSize: size});
                    }}
                    style={{padding: '8px 16px'}}
                    itemStyle={{
                        borderRadius: '4px',
                        margin: '0 2px',
                        transition: 'all 0.2s ease'
                    }}
                    prevIcon={<span style={{transition: 'transform 0.2s ease'}}>←</span>}
                    nextIcon={<span style={{transition: 'transform 0.2s ease'}}>→</span>}
                />
            </div>

            {/* 消息详情模态框 */}
            <MqDetail
                visible={messageDetailVisible}
                setVisible={setMessageDetailVisible}
                messageDetail={messageDetail}
                pageQueryMessage={pageQueryMessage}
            />
        </div>
    );
};

export default ConsoleMqPage;